import logging
import os
from datetime import datetime
import config

class MyLog(object):
    logger: logging.Logger = None
    file_handler: logging.FileHandler = None

    __instance = None

    @staticmethod
    def get_instance():
        if MyLog.__instance is None:
            MyLog()

        return MyLog.__instance

    def __init__(self):
        if MyLog.__instance is not None:
            raise Exception("Cannot create more than one instance")
        else:
            MyLog.__instance = self

    def install_logger(self):

        # 获取当前日期和时间
        now = datetime.now()
        date_string = now.strftime("%Y-%m-%d")
        output_path2 = os.path.join(config.log_path, f"{date_string}.log")

        if self.logger is None:
            logger = logging.getLogger(__name__)
            self.logger = logger
            logger.setLevel(level=logging.INFO)
            if config.is_debug:
                logger.setLevel(level=logging.DEBUG)

            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.INFO)
            if config.is_debug:
                console_handler.setLevel(logging.DEBUG)
                formatter1 = logging.Formatter('%(levelname)s : %(message)s')
                console_handler.setFormatter(formatter1)
            logger.addHandler(console_handler)

        if self.file_handler:
            self.logger.removeHandler(self.file_handler)

        file_handler = logging.FileHandler(output_path2, encoding='utf-8')
        self.file_handler = file_handler
        file_handler.setLevel(logging.INFO)
        if config.is_debug:
            file_handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s | %(levelname)s : %(message)s')
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)

    @staticmethod
    def error(msg, *args, **kwargs):
        MyLog.get_instance().logger.error(msg)

    @staticmethod
    def info(msg, *args, **kwargs):
        MyLog.get_instance().logger.info(msg)

    @staticmethod
    def debug(msg, *args, **kwargs):
        MyLog.get_instance().logger.debug(msg)


my_log = MyLog()
